<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            text-align: center;
            margin: 0;
            padding: 20px;
        }
        .container {
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 20px;
        }
        #video {
            width: 100%;
            max-width: 500px;
            background-color: #000;
            border-radius: 8px;
        }
        #canvas, #faceCanvas {
            display: none;
            max-width: 500px;
        }
        #faceResult {
            max-width: 500px;
            border-radius: 50%;
            border: 3px solid #fff;
            box-shadow: 0 0 10px rgba(0,0,0,0.3);
        }
        button {
            padding: 10px 20px;
            background-color: #4285f4;
            color: white;
            border: none;
            border-radius: 4px;
            font-size: 16px;
            cursor: pointer;
        }
        button:disabled {
            background-color: #cccccc;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>人脸拍照截取</h1>
        <video id="video" autoplay playsinline></video>
        <button id="captureBtn">拍照</button>
        <canvas id="canvas"></canvas>
        <canvas id="faceCanvas"></canvas>
        <div id="resultContainer" style="display:none;">
            <h2>截取的人脸</h2>
            <img id="faceResult" alt="人脸截图">
        </div>
    </div>

    <script>
        // 获取DOM元素
        const video = document.getElementById('video');
        const captureBtn = document.getElementById('captureBtn');
        const canvas = document.getElementById('canvas');
        const faceCanvas = document.getElementById('faceCanvas');
        const faceResult = document.getElementById('faceResult');
        const resultContainer = document.getElementById('resultContainer');

        // 视频流对象
        let stream = null;

        // 启动摄像头
        async function startCamera() {
            try {
                // 获取摄像头权限
                stream = await navigator.mediaDevices.getUserMedia({
                    video: {
                        facingMode: 'user', // 前置摄像头
                        width: { ideal: 1280 },
                        height: { ideal: 720 }
                    },
                    audio: false
                });
                
                video.srcObject = stream;
                captureBtn.disabled = false;
            } catch (err) {
                console.error("摄像头访问错误:", err);
                alert("无法访问摄像头: " + err.message);
            }
        }

        // 拍照并检测人脸
        captureBtn.addEventListener('click', async () => {
            if (!stream) return;
            
            // 暂停视频
            video.pause();
            
            // 设置canvas尺寸与视频相同
            canvas.width = video.videoWidth;
            canvas.height = video.videoHeight;
            
            // 在canvas上绘制视频帧
            const ctx = canvas.getContext('2d');
            ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
            
            try {
                // 检测人脸
                const faces = await detectFaces(canvas);
                
                if (faces.length === 0) {
                    alert("未检测到人脸，请重试!");
                    video.play();
                    return;
                }
                
                // 获取最大的人脸（假设用户是主要人脸）
                const mainFace = faces.reduce((prev, current) => 
                    (prev.width * prev.height > current.width * current.height) ? prev : current
                );
                
                // 裁剪人脸区域
                cropFace(canvas, mainFace);
                
                // 显示结果
                resultContainer.style.display = 'block';
                
            } catch (err) {
                console.error("人脸检测错误:", err);
                alert("人脸检测失败: " + err.message);
                video.play();
            }
        });

        // 使用Face Detection API检测人脸
        async function detectFaces(imageSource) {
            // 检查浏览器是否支持Face Detection API
            if (!('FaceDetector' in window)) {
                throw new Error("您的浏览器不支持人脸检测API");
            }
            
            const faceDetector = new FaceDetector({
                maxDetectedFaces: 5,
                fastMode: true
            });
            
            try {
                const faces = await faceDetector.detect(imageSource);
                return faces.map(face => face.boundingBox);
            } catch (err) {
                // 如果Face Detection API失败，尝试使用备用方法
                console.warn("Face Detection API失败:", err);
                return fallbackFaceDetection(imageSource);
            }
        }

        // 备用简单人脸检测（基于中心区域）
        function fallbackFaceDetection(imageSource) {
            // 这是一个非常简单的替代方案，实际应用中应该使用更可靠的库
            const width = imageSource.width || imageSource.videoWidth;
            const height = imageSource.height || imageSource.videoHeight;
            
            // 假设人脸在图像中央，占图像的1/3
            const faceSize = Math.min(width, height) / 3;
            const x = (width - faceSize) / 2;
            const y = (height - faceSize) / 2;
            
            return [{
                x: x,
                y: y,
                width: faceSize,
                height: faceSize
            }];
        }

        // 裁剪人脸区域
        function cropFace(sourceCanvas, faceRect) {
            faceCanvas.width = faceRect.width;
            faceCanvas.height = faceRect.height;
            
            const ctx = faceCanvas.getContext('2d');
            ctx.drawImage(
                sourceCanvas,
                faceRect.x, faceRect.y, faceRect.width, faceRect.height, // 源图像裁剪区域
                0, 0, faceRect.width, faceRect.height  // 目标canvas绘制区域
            );
            
            // 将裁剪结果转换为图片显示
            faceResult.src = faceCanvas.toDataURL('image/jpeg');
        }

        // 页面加载时启动摄像头
        window.addEventListener('DOMContentLoaded', () => {
            startCamera();
        });

        // 清理摄像头资源
        window.addEventListener('beforeunload', () => {
            if (stream) {
                stream.getTracks().forEach(track => track.stop());
            }
        });
    </script>
</body>
</html>